import hmac
import time
import hashlib
import requests
import json
from urllib.parse import urlencode, quote
from django.http import HttpResponse
import logging

KEY = ''
SECRET = ''
BASE_URL = 'https://fapi.binance.com'
logger = logging.getLogger()
fh = logging.FileHandler('./access.log')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.setLevel(logging.INFO)

def hashing(query_string):
    return hmac.new(SECRET.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()

def get_timestamp():
    return int(time.time() * 1000)

def dispatch_request(http_method):
    session = requests.Session()
    session.headers.update({
        'Content-Type': 'application/json;charset=utf-8',
        'X-MBX-APIKEY': KEY
    })
    return {
        'GET': session.get,
        'DELETE': session.delete,
        'PUT': session.put,
        'POST': session.post,
    }.get(http_method, 'GET')


def send_signed_request(http_method, url_path, payload={}):
    query_string = urlencode(payload)
    query_string = query_string.replace('%27', '%22')

    if query_string:
        query_string = "{}&timestamp={}".format(query_string, get_timestamp())
    else:
        query_string = 'timestamp={}'.format(get_timestamp())

    url = BASE_URL + url_path + '?' + query_string + '&signature=' + hashing(query_string)
    params = {'url': url, 'params': {}}
    response = dispatch_request(http_method)(**params)
    return response.json()

def send_public_request(url_path, payload={}):
    query_string = urlencode(payload, True)
    url = BASE_URL + url_path
    if query_string:
        url = url + '?' + query_string
    response = dispatch_request('GET')(url=url)
    return response.json()

def getprice():
    param = {
        "symbol": "ETHUSDT"
    }
    jsondata = send_public_request('/fapi/v1/ticker/price',param)
    return jsondata['price']

def userinfo():
    jsondata = send_signed_request('GET','/fapi/v2/balance')
    for element in jsondata:
        if element['asset'] == 'USDT':
            return element['balance']

def userswap():
    jsondata = send_signed_request('GET','/fapi/v2/account')
    for element in jsondata['positions']:
        if element['symbol'] == 'ETHUSDT':
            hadvolume = element['positionAmt']
    return abs(float(hadvolume))

def levelchange():
    param = {
        'symbol':'ETHUSDT',
        'leverage':'1',
    }
    jsondata = send_signed_request('POST','/fapi/v1/leverage',param)

def queryvolume():
    nowprice = getprice()
    balance = userinfo()
    volume = float(balance) / float(nowprice) - 0.001
    volume = float(("%.3f" % volume))
    return volume

def longswap(quantity):  # 开多
    param = {
        "symbol": "ETHUSDT",
        "side":"BUY",
        "type":"MARKET",
        "quantity":quantity
    }
    jsondata = send_signed_request('POST', '/fapi/v1/order', param)
    logger.info(jsondata)
    text = json.dumps(jsondata)
    if 'orderId' in text:
        return 1
    else:
        return 0

def shortswap(quantity):
    param = {
        "symbol": "ETHUSDT",
        "side": "SELL",
        "type": "MARKET",
        "quantity": quantity
    }
    jsondata = send_signed_request('POST', '/fapi/v1/order', param)
    logger.info(jsondata)
    text = json.dumps(jsondata)
    if 'orderId' in text:
        return 1
    else:
        return 0

def buysell(request):
    flag = 0
    request.encoding = 'utf-8'
    if request.method == 'POST':
        jsondata = json.loads(request.body)
        if jsondata['key'] == '':
            direction = jsondata['direction']
            if direction == 'buy':
                swapamt = userswap()
                if swapamt != 0:
                    longswap(swapamt)
                while flag == 0:
                    quantity = queryvolume()
                    flag = longswap(quantity)
            if direction == 'sell':
                swapamt = userswap()
                if swapamt != 0:
                    shortswap(swapamt)
                while flag == 0:
                    quantity = queryvolume()
                    flag = shortswap(quantity)
    return HttpResponse('OK')

def test(request):
    return HttpResponse('OK')